package com.wondertek.common.util.base;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@SuppressWarnings("all")
public class PoiUtil {

    public static void writeExcelToResponse(String fileName, Class clazz, List data,
                                            HttpServletResponse response){
        try {
            List<String> exclude = Arrays.stream(ReflectUtil.getFields(clazz))
                    .map(field -> field.getAnnotation(ExcelProperty.class) == null ? field.getName() : null)
                    .filter(s->s!=null)
                    .collect(Collectors.toList());
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clazz)
                    .registerConverter(new Converter<Date>() {
                        @Override
                        public Class<Date> supportJavaTypeKey() {
                            return Date.class;
                        }

                        @Override
                        public CellDataTypeEnum supportExcelTypeKey() {
                            return CellDataTypeEnum.STRING;
                        }

                        @Override
                        public WriteCellData<?> convertToExcelData(WriteConverterContext<Date> context) throws Exception {
                            return new WriteCellData<>(new DateTime(context.getValue()).toString());
                        }
                    })
                    .sheet("Sheet1")
                    .excludeColumnFieldNames(exclude)
                    .doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException(
                    String.format("导出excel表格失败! fileName:%s  clazz:%s",fileName,clazz), e);
        }
    }
}
